define(function(require, exports){
	var $		= require("jquery");
	var pubjs	= require('pubjs');
	var util	= require('util');
	var view = require('@base/view');
	var popwin	= require('@base/dialog').base;
	var adx_map = pubjs.config('channelMap');


	function boolValTypeFilter(isBoolType) {
		return !!isBoolType ? function (item) {
			return !item.ValType || item.ValType == 'bool';
		} : function (item) {
			return item.ValType && item.ValType != 'bool';
		}
	}	
	
	var Edit = popwin.extend({
		init: function( config ) {
			config = pubjs.conf( config, {
				'title': LANG('编辑ADX'),
				'adxAttributesUrl':'adexchange/getAttributes',
				'updateUrl':'adexchange/update',
				'addUrl':'adexchange/add',
				'width': 350,
				'silence': true,

				view_model:{
					attributes:[{Name:'',Text:'',Val:[]}],
					nonBoolAttributes:[{Name:'',Text:'',Val:''}]
				}
			});
			this.Super( 'init', arguments );
			this.$id = 0;
			this.loadAttributes();
		},
		afterBuild:function(){

			this.Super('afterBuild',arguments);
			var self = this;
			var el = self.getDOM();
			var html = [
				'<div class="P-dspUserCharge pl20">',
				'<div class="mb20 uk-form">',
				'<label class="M-formLabel mr10">' + LANG('渠道ID：') + '</label>',
				'<span class="M-formInput" pub-name="adxId" pub-mod="@base/common/input.text"/>',
				'</div>',
					'<div class="mb20 uk-form">',
						'<label class="M-formLabel mr10">' + LANG('渠道名称：') + '</label>',
						'<span class="M-formInput" pub-name="adxName" pub-mod="@base/common/input.text"/>',
					'</div>',
					'<div class="mb20 uk-form">',
						'<label class="M-formLabel mr10">' + LANG('属性：') + '</label>',
						'<div class="M-formInput" style="display: inline-block;">',
							'<label ms-repeat-item="attributes" style="display:block" class="mr10">',
								'<input type="checkbox" ms-duplex="item.Val" value="true">',
								'<b ms-text="item.Name" class="mr10"/>',
								'<span ms-text="item.Text"/>',
							'</label>',
							'<label ms-repeat-item="nonBoolAttributes" style="display:block" class="mr10">',
								'<b ms-text="item.Name" class="mr10"/>',
								'<span ms-text="item.Text"/>',
								'<input class="ml5" type="text" ms-duplex-string ="item.Val">',
							'</label>',
						'</div>',
					'</div>',
				'</div>'
			].join('');

			$(html).appendTo( el );
			self.buildFromTemplate({
				'adxId': {
					'width': 275
				},
				'adxName': {
					'width': 275
				}
			});

		},
		loadAttributes:function(){
			pubjs.loading.show();
			var c = this.getConfig();
			var self = this;
			pubjs.mc.send(c.adxAttributesUrl, {}, function(err,data){
				pubjs.loading.hide();
				if(err){
					pubjs.alert(err.message);
					return false;
				}
				self.$attributes = data;
			});
		},
		load: function( adxId ) {
			var self = this;
			self.$id = adxId;
		},
		onData: function( err, data ) {
			this.setData( data );
		},
		setData: function( data ) {
			var self = this;
			var mods = self.$;

			mods.adxId.setValue(data.id).disable();
			//mods.adxName.setValue(data.Name).disable();
			mods.adxName.setValue(data.Name);
			this.$id = data.id;

			var vm = this.vm.$;
			//清空属性
			vm.attributes = [];
			var attributes = this.$attributes;
			//清空选中属性
			for(var i = 0; i < attributes.length; i++) {
				var attr = attributes[i];
				if (!attr.ValType || attr.ValType == 'bool') {
					attr.Val = [];
					if (data.Attributes[attr.Name]) {
						attr.Val.push('true');
					}
				}
				else {
					attr.Val = data.Attributes[attr.Name] ||'';
				}
			}
			
			vm.attributes = attributes.filter(boolValTypeFilter(true));
			vm.nonBoolAttributes = attributes.filter(boolValTypeFilter(false));
			
			return this;
		},
		getData: function(){
			var vm = this.vm.$;
			var Attributes = {};

			for(var i = 0; i < vm.attributes.length; i++){
				var attr = vm.attributes[i];
				if (attr.Val && attr.Val[0] == 'true'){
					Attributes[attr.Name] = true;
				}
			}

			for(var i = 0; i < vm.nonBoolAttributes.length; i++){
				Attributes[vm.nonBoolAttributes[i].Name] = vm.nonBoolAttributes[i].Val || '';
			}

			var adxId = this.$.adxId.getValue();

			return {
				Name:this.$.adxName.getValue(),
				Attributes:Attributes,
				'id': this.$id || adxId
			}
		},
		reset: function(){
			this.$id = null;
			this.$.adxName.setValue('').enable();
			this.$.adxId.setValue('').enable();

			var boolAttr = this.$attributes.filter(boolValTypeFilter(true));
			for(var i = 0; i < boolAttr.length; i++){
				boolAttr[i].Val = [];
			}
			this.vm.$.attributes = boolAttr;

			var nonBoolAttr = this.$attributes.filter(boolValTypeFilter(false));
			for(var i = 0; i < nonBoolAttr.length; i++){
				nonBoolAttr[i].Val = '';
			}
			this.vm.$.nonBoolAttributes = nonBoolAttr;

			return this;
		},
		save: function(data){
			var data = this.getData();
			var cfg = this.getConfig();
			var url = this.$id ? cfg.updateUrl:cfg.addUrl;

			if(this.validate(data)){
				pubjs.loading.show();
				pubjs.mc.send(url , data, this.onSave.bind(this));
			}
		},
		onSave: function(err, data){
			pubjs.loading.hide();
			if(err){
				pubjs.alert(err.message);
				return false;
			}
			pubjs.alert(LANG('保存成功'));
			this.fire('editSuccess');
			this.reset();
			this.hide();
		},
		//响应点击完成事件
		onOk: function(ev){
			var data = this.getData();
			this.save(data);
		},
		validate: function(data){

			if(!data.Name){
				pubjs.alert(LANG('请填写渠道名称'));
				return false;
			}
			if(!data.id || !util.isNumber(data.id)){
				pubjs.alert(LANG('请填写渠道正确的渠道ID'));
				return false;
			}
			return true;
		}
	});
	exports.base = Edit;
	
	var Batch = view.widget.extend({
		init: function(config){
			config = pubjs.conf(config, {
				'url': '',
				"layout": {
					"module": '@base/dialog.base',
					"mask": 1,
					"showFoot": true, // 显示底层的取消和完成按钮
					"size": 'm',
					"close": null,
					"silence": false // 点击按钮发消息
				}
			});
			this.Super('init', arguments);
		},
		afterBuild: function() {
			var c = this.getConfig();
			var el = this.getDOM();
			$('<div pub-name="mod" pub-mod="adExchange/action/edit.batch">').appendTo(el);
			this.buildFromTemplate({ mod: {
				isPop: true
			}});
		},
		onDialogOk: function(ev){
			var self = this;
			this.$.mod.save(function() {
				self.fire('saveRecord');
			});

			this.hide();
			return false;
		},
		reload: function(id) {
			this.$.mod.load(id);
			return this;
		},
		onDialogCancel: function(){
			this.reset().hide();
		},
		reset: function(){
			this.$.mod.reset();
			return this;
		}
	});

	exports.batch = Batch;

	var BatchProp = Batch.extend({
		init: function(config){
			config = pubjs.conf(config, {
				"layout": {
					"module": '@base/dialog.base',
					"mask": 1,
					"showFoot": true, // 显示底层的取消和完成按钮
					"size": 'm',
					"close": null,
					"silence": false // 点击按钮发消息
				}
			});

			this.Super('init', arguments);
		},
		afterBuild: function() {
			var c = this.getConfig();
			var el = this.getDOM();
			$('<div pub-name="mod" pub-mod="adExchange/action/edit.batchProp">').appendTo(el);
			this.buildFromTemplate({ mod: {
				isPop: true
			}});
		}
	});

	exports.batchProp = BatchProp;

	var Alias = view.widget.extend({
		init: function(config){
			config = pubjs.conf(config, {
				'url': '',
				"layout": {
					"module": '@base/dialog.base',
					"mask": 1,
					"showFoot": true, // 显示底层的取消和完成按钮
					"size": 'm',
					"close": null,
					"silence": false // 点击按钮发消息
				},
				"view_model": {
					data: []
				}
			});
			this.Super('init', arguments);
		},
		afterBuild: function() {
			var c = this.getConfig();
			var el = this.getDOM();

			$([
				'<div ms-repeat-item="data">',
					'<span>{{item.name}}:</span>',
					'<div ms-repeat-value="item.value" class="pl20 pt10">',
						'<span class="mr20">用户Id: {{value.UserId}};</span>',
						'<span>别名：{{value.name}};</span>',
					'</div>',
				'</div>',
				'<div pub-name="mod" pub-mod="@mod/fieldEdit.base">'
			].join('')).appendTo(el);

			this.buildFromTemplate({ mod: {
				fields: [
					{text: LANG('用户Id'), type: 'input', field: 'UserId', validate: true}
					,{text: LANG('别名'), type: 'input', field: 'Value', validate: true}
					,{text: LANG('field'), type: 'input', field: 'field', defaultValue: 'Name'}
				],
				isPop: true
			}});
		},
		setData: function(data) {
			var ret = [];
			if(data && data.Alias)
			{
				for(var field in data.Alias)
				{
					if(data.Alias.hasOwnProperty(field))
					{
						var alias = data.Alias[field];
						var obj = {name: field, value: []};
						for(var UserId in alias)
						{
							if(alias.hasOwnProperty(UserId))
							{
								obj.value.push({UserId: UserId, name: alias[UserId]});
							}
						}

						ret.push(obj);
					}
				}
			}

			this.vm.$.data = ret;
			return this;
		},
		onDialogOk: function(ev){
			var self = this;
			var mod = self.$.mod;
			var data = mod.getData();
			if(mod.validate(data))
			{
				data.id = self.$id;
				self.fire('saveAlias', data);
				this.hide();
			}

			return false;
		},
		onDialogCancel: function(){
			this.reset().hide();
		},
		reset: function(id){
			this.$.mod.reset().setTitle(adx_map[id] + ' 的别名修改:');
			this.$id = id;
			return this;
		}
	});

	exports.alias = Alias;

	var CreativeLimit = view.widget.extend({
		init: function(config){
			config = pubjs.conf(config, {
				'url': '',
				"layout": {
					"module": '@base/dialog.base',
					"mask": 1,
					"showFoot": true, // 显示底层的取消和完成按钮
					"size": 'm',
					"close": null,
					"silence": false // 点击按钮发消息
				}
			});
			this.Super('init', arguments);
		},
		afterBuild: function() {
			var c = this.getConfig();
			var el = this.getDOM();
			$('<div pub-name="mod" pub-mod="@mod/fieldEdit.base">').appendTo(el);
			this.buildFromTemplate({ mod: {
				fields: [
					{text: LANG('用户Id'), type: 'input', tip: LANG('以逗号为间隔'), field: 'UserId'}
				],
				isPop: true
			}});
		},
		onDialogOk: function(ev){
			var self = this;
			var mod = self.$.mod;
			var data = mod.getData();
			if(mod.validate(data))
			{
				data.id = self.$id;
				self.fire('saveCreativeLimit', data);
				this.hide();
			}

			return false;
		},
		onDialogCancel: function(){
			this.reset().hide();
		},
		setData: function(data) {
			this.$.mod.set_field('UserId', data.DynamicCreateLimit || []);
			return this;
		},
		reset: function(id){
			this.$.mod.reset().setTitle(adx_map[id] + ' 动态创意用户限制:');
			this.$id = id;
			return this;
		}
	});

	exports.creativeLimit = CreativeLimit;
});